<template>
  <div class="chooser" :style="{ background: background }">
    <ul class="chooser-list">
      <li v-bind:style="normalCorner" v-for="(item, index) in options" :key="index" @click="optionsClick(item)"
        :class="{ active: checkActive(item) }">{{ item.text }}</li>
    </ul>
  </div>
</template>

<script>
  export default {
    name: 'TagSelect',
    model: {
      prop: 'currValArr',
      event: 'input'
    },
    data() {
      return {
        normalCorner: {
          'border-radius': '20px'
        }
      };
    },
    props: {
      currValArr: Array,
      options: Array, // 传入的数组
      background: {
        type: String,
        default: '#fff'
      },
      isMultiply: {
        // 是否是多选。默认为false：单选；true：多选
        type: Boolean,
        default: false
      },
      cssStyle: Object // 可以自定义单选或者多选的样式
    },
    mounted() {
      this.$nextTick(() => {
        this.normalCorner = this.cssStyle;
      });
    },
    methods: {
      optionsClick(item) {
        if (this.isMultiply === false) {
          // 单选
          this.$set(this.currValArr, 0, item.value); // 将该值设为当前数组的第一项
        } else {
          // 多选
          if (this.currValArr.indexOf(item.value) === -1) {
            // 当前数组中没有该值则push到数组
            this.currValArr.push(item.value);
          } else {
            // 当前数组中有该值，找到该值下标并删除
            this.currValArr.splice(this.currValArr.indexOf(item.value), 1);
          }
        }

        this.$emit('listener', this.currValArr);
      },
      checkActive(item) {
        if (this.isMultiply === false) {
          this.currValArr.length = 1;
        }
        return this.currValArr.indexOf(item.value) !== -1;
      }
    }
  };

</script>

<style lang="less">
  .chooser {
    position: relative;
    display: inline-block;
    background-size: 80%;
    padding: 4px 16px 0 16px;
    border-radius: 24px;

    .chooser-list {
      margin: 0;
      padding: 0;
      display: flex;
      justify-content: flex-start;
      align-items: center;
      flex-wrap: nowrap;
    }

    .chooser-list li {
      list-style: none;
      margin: 0 6px 0 6px;
      padding-left: 15px;
      padding-right: 15px;
      width: auto;
      min-width: 50px;
      height: 28px;
      line-height: 28px;
      border-radius: 5px;
      font-size: 12px;
      // display: inline-block;
      color: #555;
      text-align: center;
      cursor: pointer;
      -moz-user-select: none;
      -khtml-user-select: none;
      user-select: none;
      overflow: hidden;

      /* 超出部分隐藏 */
      white-space: nowrap;

      /* 不换行 */
      text-overflow: ellipsis;

      /* 超出部分文字以...显示 */
      &:hover {
        color: #ccc;
      }

      &.active {
        border: 1px solid  #2d8cf0;;
        border-color: #2d8cf0;
        color: #2d8cf0;
        // background: #ccc;
        // box-shadow: 0px 4px 10px rgba(5, 54, 37, 0.1);
      }
    }
  }

</style>
